//
//  CZComposeViewController.swift
//  Weibo27
//
//  Created by apple on 16/4/23.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit
import SVProgressHUD
class CZComposeViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
    }
    
    // MARK: - 监听方法
    @objc private func cancel(){
        
        // 取消composeTextView 第一响应
        composeTextView.resignFirstResponder()
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    @objc private func send(){
        
        /*
        
            添加一个表情图片 a[表]a
        
            a[马上有对象]a
        */
        // 创建一个可变字符串保存我们遍历的到的字符串
        var result: String = String()
        //  a[表情]a
        // 遍历attributedText 得对每次遍历到的对象 和对应的位置
        composeTextView.attributedText.enumerateAttributesInRange(NSMakeRange(0, composeTextView.attributedText.length), options: []) { (dictInfo, range, _) -> Void in
            if let att = dictInfo["NSAttachment"] as? CZTextAttachment{
                result += att.emoticon?.chs ?? ""
            }else{
                // 从我们的富文本中 截取出里面的文字
                let name = (self.composeTextView.attributedText.string as NSString).substringWithRange(range)

                result += name

            }
        }
    
        //print(composeTextView.attributedText)
        //a[马上有对象][带着微博去旅行]a
      //  print("发送按钮点击啦")
        // 如果配图数据的count 不等于0 就代表是会发布图片微博
        if composePictureView.images.count != 0{
            upload(result)
        }else{
            update(result)
        }
        
        
    }
    
    
    // MARK: - 设置视图
    private func setupUI(){
        setupNav()
        view.backgroundColor = UIColor.whiteColor()
        // 添加控件
        view.addSubview(composeTextView)
        view.addSubview(composeToolBar)
        composeTextView.addSubview(composePictureView)
        // 添加约束
        // 在ios7 以后 系统检测你如果有导航栏 他直接叫你显示的文字下移
        composeTextView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(view).offset(UIEdgeInsetsZero)
        }
        
        composeToolBar.snp_makeConstraints { (make) -> Void in
            make.leading.trailing.bottom.equalTo(view)
            make.height.equalTo(44)
        }
        
        composePictureView.snp_makeConstraints { (make) -> Void in
            make.size.equalTo(CGSize(width: SCREENW - 20, height: SCREENW - 20))
            make.leading.equalTo(10)
            make.top.equalTo(composeTextView).offset(100)
        }
        
        // 监听toolbar 按钮点击
        composeToolBar.composeToolBarColsure = {[weak self](type: CZComposeToolBarType) in
            switch type{
            case .Picture:
                self?.selectImage()
            case .Mention:
                print("@")
            case .Trend:
                print("#")
            case .Emoticon:
                self?.switchKeyborad()
            case .Add:
                print("+")
            }
        }
        
        // 监听弹出图片控制器
        composePictureView.ComposePictureViewClosure = { [weak self] in
            self?.selectImage()
        }
        
        // 监听键盘弹出frame改变
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillChangeFrame:", name: UIKeyboardWillChangeFrameNotification, object: nil)
        
        // 表情键盘删除按钮通知接收
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "emoticonDeleteButtonClick", name: EmoticonDeleteButtonNSNotification, object: nil)
        
        // 表情键盘表情按钮通知接收
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "emoticonButtonClick:", name: EmoticonButtonNSNotification, object: nil)
        
        
        
        
    }
    // 监听表情键盘删除按钮点击
    func emoticonDeleteButtonClick(){
        // 回删
        composeTextView.deleteBackward()
    }
    // 监听表情键盘的按钮点击
    func emoticonButtonClick(noti: NSNotification){
        
        guard let emoticon = noti.object as? CZEmoticon else{
            return
        }
        // 代表是emoji表情
        if emoticon.isEmoji{
            // 把十六进制的字符串转成emoji表情
            let code = ((emoticon.code ?? "") as NSString).emoji()
            // 插入emoji表情
            composeTextView.insertText(code)
        }else{
            // 图片表情
            
            // 得到我们以前的富文本
            
            let oldAttr = NSMutableAttributedString(attributedString: composeTextView.attributedText)
            
            // 01 初始化一个image
            let path = "\(emoticon.path ?? "")\(emoticon.png ?? "")"
            let image = UIImage(named: path, inBundle: CZEmoticonTools.sharedTools.emoticonBundle, compatibleWithTraitCollection: nil)
            
            // 得到行高
            let lineHeight = composeTextView.font!.lineHeight
            // 02 初始化一个文本附件
            let att = CZTextAttachment()
            
            // 给我们自定义的文本附件设置emoticon
            att.emoticon = emoticon
            //     - 设置bounds
            att.bounds = CGRect(x: 0, y: -4, width: lineHeight, height: lineHeight)
            //     - 设置image
            att.image = image
            // 03 初始化一个不可变富文本
            let attr = NSAttributedString(attachment: att)
            // 添加到后面(由于光标问题 该方法不可行)
           // oldAttr.appendAttributedString(attr)
            // 获取textView 的光标
            let selectedRange = composeTextView.selectedRange
            // 插入富文本(由于选中多个的时候 该方法不可行)
          //  oldAttr.insertAttributedString(attr, atIndex: selectedRange.location)
            // 替换选中部分的富文本
            oldAttr.replaceCharactersInRange(selectedRange, withAttributedString: attr)
            
            // 设置富文本字体
            oldAttr.addAttribute(NSFontAttributeName, value: composeTextView.font!, range: NSMakeRange(0, oldAttr.length))
            
            composeTextView.attributedText = oldAttr

            composeTextView.selectedRange = NSMakeRange(selectedRange.location + 1, 0)
            
            // 发送一个系统通知 把占位文字隐藏
            NSNotificationCenter.defaultCenter().postNotificationName(UITextViewTextDidChangeNotification, object: nil)
            
            // 改变右侧发送按钮的状态
            // 偷懒方式
           // textViewDidChange(composeTextView)
            composeTextView.delegate?.textViewDidChange!(composeTextView)
        }
        
        
        
        
    }
    
    
    // 监听键盘弹出frame改变方法
    func keyboardWillChangeFrame(noti: NSNotification){
        // 获取键盘的rect
        let rect = (noti.userInfo!["UIKeyboardFrameEndUserInfoKey"] as! NSValue).CGRectValue()
        // 更新composeToolBar约束
        composeToolBar.snp_updateConstraints { (make) -> Void in
            make.bottom.equalTo(view).offset(rect.origin.y - SCREENH)
        }
        UIView.animateWithDuration(0.25) { () -> Void in
            self.view.layoutIfNeeded()
        }
    }
    
    // MARK: - 设置导航栏
    private func setupNav(){
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "cancel")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发送", style: UIBarButtonItemStyle.Plain, target: self, action: "send")
        navigationItem.rightBarButtonItem?.enabled = false
        navigationItem.titleView = titleView
        
    }
    
    // MARK: - 懒加载控件
    // titleView
    private lazy var titleView: UILabel = {
        // 用户昵称
        let name = CZUserAccountTools.sharedTools.userAccount?.screen_name ?? ""
        // 发微博
        let titleString = "发微博\n\(name)"
        // 富文本
        let attr = NSMutableAttributedString(string: titleString)
        
        // 获取range
        let range = (titleString as NSString).rangeOfString(name)
        
        //设置指定位置的颜色 和字体大小
        attr.addAttribute(NSFontAttributeName, value: UIFont.systemFontOfSize(12), range: range)
        attr.addAttribute(NSForegroundColorAttributeName, value: ThemeColor, range: range)
        let lab = UILabel(textColor: UIColor.darkGrayColor(), textFont: 15)
        lab.attributedText = attr
        lab.numberOfLines = 0
        lab.textAlignment = .Center
        lab.sizeToFit()
        return lab
    }()
    
    // 文本输入框
    private lazy var composeTextView: CZComposeTextView = {

        let view = CZComposeTextView()
        view.font = UIFont.systemFontOfSize(16)
        view.delegate = self
        view.placeholder = "我是老王 我为自己代言我是老王 我为自己代言我是老王 我为自己代言我是老王 我为自己代言我是老王 我为自己代言"
        view.alwaysBounceVertical = true
        return view
    }()
    
    // 底部toolbar
    private lazy var composeToolBar: CZComposeToolBar = CZComposeToolBar()
    
    // 配图
    private lazy var composePictureView: CZComposePictureView = CZComposePictureView()
    
    // 自定义表情键盘
    private lazy var emoticonKeyboard: CZEmoticonKeyboardView = {
        let view = CZEmoticonKeyboardView()
        view.frame = CGRect(x: 0, y: 0, width: SCREENW, height: 216)
        return view
    }()
    deinit{
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    
}
// MARK: - UITextViewDelegate
extension CZComposeViewController: UITextViewDelegate{
    func textViewDidChange(textView: UITextView) {
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
    }
    
    func scrollViewDidScroll(scrollView: UIScrollView) {
        composeTextView.resignFirstResponder()
    }
}
// MARK: - 处理toolbar 里面的按钮点击事件
extension CZComposeViewController{
    // 选择image
    func selectImage() {
        let pickerVc =  UIImagePickerController()
        pickerVc.delegate = self
        
        if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.Camera){
            
        }else{
            //print("不能打开照相机")
            presentViewController(pickerVc, animated: true, completion: nil)
        }
    }
    
    // 切换键盘
    func switchKeyborad(){
       // composeTextView.inputView = emoticonKeyboard
        
        /*
            - composeTextView.inputView == nil  代表当前是系统键盘  给他改成自定义表情键盘
            - composeTextView.inputView != nil  代表当前是自定义表情键盘  给他改成系统键盘
        */
        // 表情键盘
        if composeTextView.inputView == nil{
            composeTextView.inputView = emoticonKeyboard
            composeToolBar.isEmoticon = true
        }else{
            // 系统键盘
            composeTextView.inputView = nil
            composeToolBar.isEmoticon = false
        }
        // 刷新InputViews
        composeTextView.reloadInputViews()
        // 当我们点击该按钮的时候叫键盘弹出 需要成为第一响应者
        composeTextView.becomeFirstResponder()
    }
    
}

extension CZComposeViewController:UIImagePickerControllerDelegate,UINavigationControllerDelegate{
    // 用户选择图片后回调方法
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {

//        let data = UIImagePNGRepresentation(getImageScale(image, width: 600))
//        
//       // /Users/apple/Desktop/student.sqlite
//        data?.writeToFile("/Users/apple/Desktop/1.png", atomically: true)
//        print(image)
        composePictureView.addImage(getImageScale(image, width: 600))
        
        picker.dismissViewControllerAnimated(true, completion: nil)
    }
    // 压缩图片
    func getImageScale(image: UIImage, width: CGFloat) -> UIImage{
        // 如果我们的图片宽度小于我们制定的宽度我们直接返回 不处理
        if image.size.width < width{
            return image
        }
        
        /*
            1200  400   
            600   x
        */
        let height = (image.size.height * width) / image.size.width
        
        
        // 01 开启上下文
        UIGraphicsBeginImageContext(CGSize(width: width, height: height))
        // 02 把image渲染到上下文中
        image.drawInRect(CGRect(x: 0, y: 0, width: width, height: height))
        // 03 得到结果
        let result = UIGraphicsGetImageFromCurrentImageContext()
        // 04 关闭上下文
        UIGraphicsEndImageContext()
       return result
    }
}

extension CZComposeViewController{
    // 发布一条文字微博
    func update(status: String){
        // 请求url
        let urlString = "https://api.weibo.com/2/statuses/update.json"
        // 请求参数
        let params = [
            "access_token": CZUserAccountTools.sharedTools.accessToken!,
            "status":status
        ]
        
        CZNetworkTools.sharedTools.request(CZRequestMethod.POST, urlString: urlString, params: params) { (response, error) -> () in
            if error != nil{
                
                SVProgressHUD.showErrorWithStatus("发送失败")
                return
            }
            
            SVProgressHUD.showSuccessWithStatus("发送成功")
        }
    }
    // 发布一条文字和图片微博
    func upload(status: String){
        // 请求url
        let urlString = "https://upload.api.weibo.com/2/statuses/upload.json"
        // 请求参数
        let params = [
            "access_token": CZUserAccountTools.sharedTools.accessToken!,
            "status":status
        ]
        
        CZNetworkTools.sharedTools.POST(urlString, parameters: params, constructingBodyWithBlock: { (formdata) -> Void in
            
            /*
                01 data- 代表我们需要上传的二进制数据
                02 name- 移动开发人员和服务器开发人员协商好的 名字
                03 filename- 服务器保存我们删除的二进制数据的路径文件夹 可以随意填写
                04 mimeType- image/jpeg(大类型/ 小类型)
            */
            //pic	true	binary	要上传的图片，仅支持JPEG、GIF、PNG格式，图片大小小于5M。
            // 通过image 得到二进制数据
            // 上传单张图片
//            let data = UIImagePNGRepresentation(self.composePictureView.images.last!)!
//            // 使用表单形式发送图片
//            formdata.appendPartWithFileData(data, name: "pic", fileName: "xxx", mimeType: "image/jpeg")
            
            // 上传多张图片
            for i in self.composePictureView.images{
                let data = UIImagePNGRepresentation(i)!
                formdata.appendPartWithFileData(data, name: "pic", fileName: "xxx", mimeType: "image/jpeg")
            }
            
            }, progress: nil, success: { (_, response) -> Void in
                SVProgressHUD.showSuccessWithStatus("发送成功")
            }) { (_, error) -> Void in
                SVProgressHUD.showErrorWithStatus("发送失败")
        }
        
        
    }
   
    
    
    
    
    
    
    
}
